/**
 * Copyright (c) 2023 - present All rights reserved.
 * <p>
 * Reprinted has been protected by the copyright laws.
 */

package cn.myxl.smart.devkit.commit.submission;

import cn.myxl.smart.devkit.commit.model.CommitType;
import cn.myxl.smart.devkit.commit.model.SettingState;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vcs.ProjectLevelVcsManager;
import com.intellij.openapi.vcs.impl.ProjectLevelVcsManagerImpl;
import git4idea.GitLocalBranch;
import git4idea.branch.GitBranchUtil;
import git4idea.repo.GitRepository;

import javax.swing.*;
import java.util.List;

/**
 * @author zhangyang
 * @date 2023-11-14 16:16
 */

public class CommitDialogUI {
	private JPanel mainPanel;
	private JComboBox<CommitType> changeType;
	private JTextField changeScope;
	private JTextField shortDescription;
	private JTextField closedIssues;
	private JTextField breakingChanges;
	private JTextArea longDescription;
	private JCheckBox branchCheckBox;

	public CommitDialogUI(Project project, SettingState settingState) {

		//parameter
		List<CommitType> typeAliases = settingState.getTypeAliases();

		for (CommitType type : typeAliases) {
			changeType.addItem(type);
		}

		longDescription.setBorder(changeScope.getBorder());

		String branchName = getBranchName(project);

		branchCheckBox.setSelected(true);
		changeScope.setText(branchName);

		branchCheckBox.addActionListener(actionEvent -> {
			if (branchCheckBox.isSelected()) {
				changeScope.setText(branchName);
			} else {
				changeScope.setText("");
			}
		});
	}

	JPanel getMainPanel() {
		return mainPanel;
	}


	CommitMessage getCommitMessage(SettingState settings) {
		return new CommitMessage(settings, (CommitType) changeType.getSelectedItem(), changeScope.getText().trim(), shortDescription.getText().trim(), longDescription.getText().trim(), closedIssues.getText().trim(), breakingChanges.getText().trim());
	}

	protected String getBranchName(Project project) {
		String branch = "";
		ProjectLevelVcsManager instance = ProjectLevelVcsManagerImpl.getInstance(project);
		if (instance.checkVcsIsActive("Git")) {
			GitRepository currentRepository = GitBranchUtil.getCurrentRepository(project);
			if (currentRepository != null) {
				GitLocalBranch currentBranch = currentRepository.getCurrentBranch();
				if (currentBranch != null) {
					branch = currentBranch.getName().trim();
				}
			}
		}
		return branch;
	}
}
